package com.kotlin.book.adapter

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.activity.DetailActivity
import com.kotlin.book.databinding.ItemBookColumn4Binding
import com.kotlin.book.entry.Book
import com.kotlin.book.util.Util

class BookItemColumn4Adapter(
    private val config: Map<String, Boolean>? = mapOf(
        "authorName" to true
    ), private var itemList: List<Book>
) : RecyclerView.Adapter<BookItemColumn4Adapter.ItemViewHolder>() {

    class ItemViewHolder(itemBinding: ItemBookColumn4Binding) :
        RecyclerView.ViewHolder(itemBinding.root) {
        val bookName: TextView = itemBinding.bookName
        val authorName: TextView = itemBinding.authorName
        val bookImage: ImageView = itemBinding.bookImage
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val binding =
            ItemBookColumn4Binding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ItemViewHolder(binding)
    }


    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = itemList[position]
        holder.bookName.text = item.name
        holder.authorName.text = item.author
        if (config?.get("authorName") == false) {
            holder.authorName.visibility = View.GONE
        }
        Util.getImage(item.pic, holder.bookImage, holder.itemView.context)

        holder.itemView.setOnClickListener {
            // 页面跳转
            val intent = Intent(holder.itemView.context, DetailActivity::class.java)
            val bundle = Bundle()
            // 传参
            bundle.putInt("id", item.id)
            intent.putExtras(bundle)
            holder.itemView.context.startActivity(intent)
        }
    }


    // 返回数据集的大小
    override fun getItemCount() = itemList.size

    fun setData(data: List<Book>) {
        itemList = data
        notifyDataSetChanged()
    }
}